package algocasts;

import java.util.*;

public class P151_LetterCombinationsOfAPhoneNumber {
    private final String[] mapping = new String[]{
            "abc", "def", "ghi", "jkl",
            "mno", "pqrs", "tuv", "wxyz"
    };

    private void combinations(String digits, int idx,
                              String str, List<String> result) {
        if (idx == digits.length()) {
            result.add(str);
            return;
        }
        String chars = mapping[digits.charAt(idx) - '2'];
        for (int i = 0; i < chars.length(); i++) {
            combinations(digits, idx + 1, str + chars.charAt(i), result);
        }
    }

    // Time: O(4^n)  Space: O(n)
    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0) return Collections.emptyList();
        List<String> result = new ArrayList<>();
        combinations(digits, 0, "", result);
        return result;
    }

    // Time: O(4^n)  Space: O(4^n)
    public List<String> letterCombinations_Iterative(String digits) {
        if (digits == null || digits.length() == 0) return Collections.emptyList();
        LinkedList<String> result = new LinkedList<>();
        result.add("");
        for (int i = 0; i < digits.length(); i++) {
            String chars = mapping[digits.charAt(i) - '2'];
            int size = result.size();
            for (int j = 0; j < size; j++) {
                String str = result.poll();
                for (int k = 0; k < chars.length(); k++) {
                    result.add(str + chars.charAt(k));
                }
            }
        }
        return result;
    }

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
    }


    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int level = 1;
        while (!q.isEmpty()) {
            int size = q.size();
            LinkedList<Integer> list = new LinkedList<>();
            for (int i = 0; i < size; ++i) {
                TreeNode node = q.poll();
                if (node.left != null) q.add(node.left);
                if (node.right != null) q.add(node.right);

                if (level % 2 != 0) {
                    list.addLast(node.val);
                } else {
                    list.addFirst(node.val);
                }

            }
            res.add(list);
            level++;
        }
        return res;
    }


}
